package com.bigdata.controller;/**
 * Created by Administrator on 2019/7/18 0018.
 */

import com.bigdata.common.constant.Constants;
import com.bigdata.model.Result;
import com.bigdata.model.User;
import com.bigdata.service.mysql.JkfwUserService;
import com.bigdata.security.jwt.AccessToken;
import com.bigdata.security.jwt.JwtConfig;
import com.bigdata.security.jwt.JwtUtil;
import com.bigdata.model.AjaxResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Administrator
 * @description
 * @date 2019/7/18 0018
 **/
@RestController
@RequestMapping("/oauth2")
public class OAuth2Controller extends BaseController {

    @Autowired
    JkfwUserService jkfwUserService;
    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    JwtConfig jwtConfig;

    @RequestMapping("/accessToken")
    public Object token(HttpServletRequest request, String username, String password) {
        if (!StringUtils.isNoneBlank(username) || !StringUtils.isNoneBlank(password)) {
            AjaxResult.fail("用户名或密码不能为空！");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < Constants.USERNAME_MIN_LENGTH || username.length() > Constants.USERNAME_MAX_LENGTH) {
            AjaxResult.fail("用户名限制2-20字符之间！");
        }
        if (password.length() < Constants.PASSWORD_MIN_LENGTH || password.length() > Constants.PASSWORD_MAX_LENGTH) {
            AjaxResult.fail("密码限制5-20字符之间！");
        }
        Result res = jkfwUserService.ckLoginToken(username, password);
        if (res.getCode() == Result.Code_OK) {
            try {
                String token = jwtUtil.generateAccessToken((User) res.getData());
                AccessToken accessToken = new AccessToken();
                accessToken.setAccessToken(token);
                accessToken.setExpiresIn(jwtConfig.getExpiration());
                accessToken.setTokenType("token");
                return accessToken;
            } catch (Exception e) {
                return AjaxResult.fail("生成token失败!");
            }
        } else {
            return AjaxResult.fail(res.getMessage());
        }
    }
}
